<template>
  <div class="page-container">
    <div class="page-header">
      <h2 class="page-title">题库管理</h2>
      <el-tag type="info" class="admin-tag">仅校级管理员可用</el-tag>
      <div class="page-actions">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          添加题目
        </el-button>
      </div>
    </div>

    <el-card>
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="题目关键词">
          <el-input v-model="searchForm.keyword" placeholder="请输入题目关键词" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="questionList" border style="width: 100%" v-loading="loading">
        <el-table-column prop="questionId" label="ID" width="80" />
        <el-table-column prop="section" label="分区" width="80">
          <template #default="{ row }">
            第{{ row.section }}章
          </template>
        </el-table-column>
        <el-table-column prop="description" label="题目内容" min-width="300" show-overflow-tooltip />
        <el-table-column label="选项" width="200">
          <template #default="{ row }">
            <div class="option-container">
              <div class="option">
                <span class="option-label">A:</span>
                <span class="option-content">{{ row.optionA }}</span>
              </div>
              <div class="option">
                <span class="option-label">B:</span>
                <span class="option-content">{{ row.optionB }}</span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="选项对应维度" width="140">
          <template #default="{ row }">
            <div>A → {{ row.affectsA }}</div>
            <div>B → {{ row.affectsB }}</div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        class="pagination"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        layout="total"
      />
    </el-card>

    <!-- 题目表单对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
    >
      <el-form
        ref="questionFormRef"
        :model="questionForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="分区" prop="section">
          <el-select v-model="questionForm.section" placeholder="请选择分区">
            <el-option
              label="第1分区 (外向E-内向I)"
              :value="1"
            />
            <el-option
              label="第2分区 (感觉S-直觉N)"
              :value="2"
            />
            <el-option
              label="第3分区 (思考T-情感F)"
              :value="3"
            />
            <el-option
              label="第4分区 (判断J-知觉P)"
              :value="4"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="题号" prop="number">
          <el-input-number v-model="questionForm.number" :min="1" :max="100" />
        </el-form-item>
        <el-form-item label="题目内容" prop="description">
          <el-input
            v-model="questionForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入题目内容"
          />
        </el-form-item>
        <el-form-item label="选项A" prop="optionA">
          <el-input
            v-model="questionForm.optionA"
            type="textarea"
            :rows="2"
            placeholder="请输入选项A的内容"
          />
        </el-form-item>
        <el-form-item label="选项B" prop="optionB">
          <el-input
            v-model="questionForm.optionB"
            type="textarea"
            :rows="2"
            placeholder="请输入选项B的内容"
          />
        </el-form-item>
        <el-form-item label="A影响维度" prop="affectsA">
          <el-select v-model="questionForm.affectsA" placeholder="请选择维度">
            <el-option
              v-for="option in availableDimensions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="B影响维度" prop="affectsB">
          <el-select v-model="questionForm.affectsB" placeholder="请选择维度">
            <el-option
              v-for="option in availableDimensions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import request from '../../utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

// 数据
const questionList = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(100);
const loading = ref(false);
const dialogVisible = ref(false);
const dialogTitle = ref('添加题目');
const questionFormRef = ref(null);
const isAdd = ref(true);

// 表单
const searchForm = ref({
  keyword: ''
});

const questionForm = ref({
  questionId: null,
  section: 1,
  number: 1,
  description: '',
  optionA: '',
  optionB: '',
  affectsA: '',
  affectsB: ''
});

// 分区对应的维度选项
const sectionDimensions = {
  1: ['E', 'I'],  // 第1分区：外向-内向
  2: ['S', 'N'],  // 第2分区：感觉-直觉
  3: ['T', 'F'],  // 第3分区：思考-情感
  4: ['J', 'P']   // 第4分区：判断-知觉
};

// 维度的中文说明
const dimensionLabels = {
  'E': '外向',
  'I': '内向',
  'S': '感觉',
  'N': '直觉',
  'T': '思考',
  'F': '情感',
  'J': '判断',
  'P': '知觉'
};

// 计算当前分区可选的维度选项
const availableDimensions = computed(() => {
  const section = questionForm.value.section;
  if (!section) return [];
  return sectionDimensions[section].map(dim => ({
    label: `${dim} (${dimensionLabels[dim]})`,
    value: dim
  }));
});

// 监听分区变化，自动清空和限制维度选择
watch(() => questionForm.value.section, () => {
  questionForm.value.affectsA = '';
  questionForm.value.affectsB = '';
});

const rules = {
  section: [
    { required: true, message: '请选择分区', trigger: 'change' }
  ],
  number: [
    { required: true, message: '请输入题号', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入题目内容', trigger: 'blur' }
  ],
  optionA: [
    { required: true, message: '请输入选项A的内容', trigger: 'blur' }
  ],
  optionB: [
    { required: true, message: '请输入选项B的内容', trigger: 'blur' }
  ],
  affectsA: [
    { required: true, message: '请选择A选项影响的维度', trigger: 'change' }
  ],
  affectsB: [
    { required: true, message: '请选择B选项影响的维度', trigger: 'change' }
  ]
};

// 方法
const loadQuestions = async () => {
  loading.value = true;
  try {
    const params = {};
    if (searchForm.value.keyword) {
      params.keyword = searchForm.value.keyword;
    }
    
    const response = await request.get('/questions/search', { params });
    questionList.value = response.data || [];
    total.value = questionList.value.length || 0;
  } catch (error) {
    console.error('搜索题目失败:', error);
    ElMessage.error('搜索题目失败');
  } finally {
    loading.value = false;
  }
};

const handleSearch = () => {
  loadQuestions();
};

const resetSearch = () => {
  searchForm.value = {
    keyword: ''
  };
  handleSearch();
};

const handleAdd = () => {
  isAdd.value = true;
  dialogTitle.value = '添加题目';
  questionForm.value = {
    questionId: null,
    section: 1,
    number: 1,
    description: '',
    optionA: '',
    optionB: '',
    affectsA: '',
    affectsB: ''
  };
  dialogVisible.value = true;
};

const handleEdit = (row) => {
  isAdd.value = false;
  dialogTitle.value = '编辑题目';
  questionForm.value = { ...row };
  dialogVisible.value = true;
};

const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除这道题目吗？此操作不可恢复！', '警告', {
    type: 'warning',
    confirmButtonText: '确定删除',
    cancelButtonText: '取消'
  }).then(async () => {
    try {
      await request.delete(`/questions/${row.questionId}`);
      ElMessage.success('删除成功');
      loadQuestions();
    } catch (error) {
      console.error('删除题目失败:', error);
      ElMessage.error('删除题目失败');
    }
  });
};

const handleSubmit = async () => {
  if (!questionFormRef.value) return;
  
  await questionFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 打印表单数据，用于调试
        console.log('提交的表单数据:', questionForm.value);
        
        // 确保维度值不为空
        if (!questionForm.value.affectsA || !questionForm.value.affectsB) {
          ElMessage.error('请选择维度值');
          return;
        }
        
        // 确保维度值是单个字母
        if (questionForm.value.affectsA.length !== 1 || questionForm.value.affectsB.length !== 1) {
          ElMessage.error('维度值必须是单个字母');
          return;
        }
        
        // 确保A选项和B选项不选择相同的维度
        if (questionForm.value.affectsA === questionForm.value.affectsB) {
          ElMessage.error('A选项和B选项不能选择相同的维度');
          return;
        }
        
        if (isAdd.value) {
          await request.post('/questions', questionForm.value);
          ElMessage.success('添加成功');
        } else {
          await request.put(`/questions/${questionForm.value.questionId}`, questionForm.value);
          ElMessage.success('更新成功');
        }
        dialogVisible.value = false;
        loadQuestions();
      } catch (error) {
        console.error('保存题目失败:', error);
        if (error.response) {
          console.error('错误响应:', error.response.data);
        }
        ElMessage.error('保存题目失败');
      }
    }
  });
};

// 监听A选项维度变化，如果与B选项维度相同，则清空B选项维度
watch(() => questionForm.value.affectsA, (newValue) => {
  if (newValue && newValue === questionForm.value.affectsB) {
    questionForm.value.affectsB = '';
    ElMessage.warning('A选项和B选项不能选择相同的维度');
  }
});

// 监听B选项维度变化，如果与A选项维度相同，则清空A选项维度
watch(() => questionForm.value.affectsB, (newValue) => {
  if (newValue && newValue === questionForm.value.affectsA) {
    questionForm.value.affectsA = '';
    ElMessage.warning('A选项和B选项不能选择相同的维度');
  }
});

// 生命周期
onMounted(() => {
  loadQuestions();
});
</script>

<style scoped>
.page-container {
  padding: 20px;
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  margin: 0;
  margin-right: 15px;
}

.admin-tag {
  margin-right: auto;
}

.page-actions {
  display: flex;
  gap: 10px;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.option-container {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.option {
  display: flex;
  align-items: flex-start;
}

.option-label {
  flex-shrink: 0;
  font-weight: bold;
  margin-right: 8px;
}

.option-content {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style> 